package com.ycwl.freetv.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;


/**
 * Created On: 2024/1/23 20:55 <br>
 * Desc      :
 *
 * @author wyl
 */
public class CrashExceptionHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashExceptionHandler";
    private Context mContext;


    private static CrashExceptionHandler myCrashHandler;

    private Thread.UncaughtExceptionHandler mDefaultException;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };

    private CrashExceptionHandler() {
    }

    public synchronized static CrashExceptionHandler newInstance() {
        if (myCrashHandler == null) {
            myCrashHandler = new CrashExceptionHandler();
        }
        return myCrashHandler;
    }


    public void init(Context context) {
        this.mContext = context;
        // 系统默认处理类
        this.mDefaultException = Thread.getDefaultUncaughtExceptionHandler();
        // 将该类设置为系统默认处理类
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        if (!dealException(e) && mDefaultException != null) {
            mDefaultException.uncaughtException(t, e);
        } else {
            try {
                Thread.sleep(3000);
            } catch (Exception exception) {
                Log.e(TAG, "uncaughtException: exception" + exception);
            }
            restartApp();
        }
    }

    /**
     * 异常处理
     *
     * @param ex
     */
    private boolean dealException(Throwable ex) {
        Log.e(TAG, "dealException ,Throwable = " + ex.getMessage());
        restartApp();
        return true;
    }

    private void restartApp() {
        handler.postDelayed(() -> {
            Log.i(TAG, "restartApp");
            Intent toIntent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
            mContext.startActivity(toIntent);
        }, 2000);
    }

}

